package com.wiscamp.ninechapters.problems.infrastructure.mappers.collections;

import com.wiscamp.ninechapters.problems.infrastructure.po.collections.ProblemCollectionView;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.Collection;

/**
 * 题集仓储对象
 *
 * @author yifeng
 */
@Repository
public interface ProblemCollectionViewMapper extends JpaRepository<ProblemCollectionView, Long>, JpaSpecificationExecutor<ProblemCollectionView> {
    /**
     * 通过代码获取题集
     *
     * @param collectionCode
     * @param organizationId
     * @return
     */
    @Query(value = "select e from ProblemCollectionView e where e.organizationId = :organizationId and e.collectionCode = :collectionCode and e.deleted = false")
    ProblemCollectionView findByCollectionCode(String collectionCode, long organizationId);

    /**
     * 通过名称获取题集列表
     *
     * @param collectionName
     * @param organizationId
     * @return
     */
    @Query(value = "select e from ProblemCollectionView e where e.organizationId = :organizationId and e.collectionName = :collectionName and e.deleted = false")
    Collection<ProblemCollectionView> findListByCollectionName(String collectionName, long organizationId);

    /**
     * 通过机构编号获取题集列表
     *
     * @param organizationId
     * @return
     */
    @Query(value = "select e from ProblemCollectionView e where e.organizationId = :organizationId and e.deleted = false")
    Collection<ProblemCollectionView> findListByOrganization(long organizationId);

    /**
     * 分页获取考试列表
     *
     * @param spec
     * @param pageable
     * @return
     */
    Page<ProblemCollectionView> findAll(Specification<ProblemCollectionView> spec, Pageable pageable);

    /**
     * 通过机构编号和题集名称模糊查询有效题集列表
     *
     * @param name
     * @param organizationId
     * @return
     */
    @Query(value = "select e from ProblemCollectionView e where e.organizationId = :organizationId and e.collectionName like :name and e.enabled = true and e.deleted = false order by e.collectionCode desc")
    Collection<ProblemCollectionView> findListByNameContains(String name, long organizationId);


    @Query(value = "select e from ProblemCollectionView e where e.examId = :examId and e.enabled order by e.collectionName desc")
    Collection<ProblemCollectionView> findListByExam(long examId);
}